package com.general.framework.zzm;

import java.util.concurrent.CountDownLatch;

/**
 * volatile变量自增运算测试
 *
 * @author zzm
 */
public class VolatileTest {
    public static volatile int race = 0;

    public static void increase() {
        race++;
    }

    private static final int THREADS_COUNT = 20;

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[THREADS_COUNT];
        // 创建CountDownLatch，初始值设置为线程数量
        CountDownLatch countDownLatch = new CountDownLatch(THREADS_COUNT);
        for (int i = 0; i < THREADS_COUNT; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    increase();
                }
                // 每个子线程完成任务后，调用countDown方法，使计数器减1
                countDownLatch.countDown();
            });
            threads[i].start();
        }
        // 主线程阻塞，等待所有子线程都完成任务（计数器归零）
        countDownLatch.await();
        System.out.println(race);
    }
}